/**
 * Copyright 2009 Henning Teek, Ingo Renner
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.googlecode.chigs.web.admin.configlocation;

import java.util.Arrays;
import java.util.List;

import org.apache.wicket.authorization.strategies.role.annotations.AuthorizeInstantiation;
import org.apache.wicket.markup.html.basic.Label;
import org.apache.wicket.markup.html.form.ChoiceRenderer;
import org.apache.wicket.markup.html.form.DropDownChoice;
import org.apache.wicket.markup.html.form.TextField;
import org.apache.wicket.markup.html.image.Image;
import org.apache.wicket.markup.html.link.Link;
import org.apache.wicket.markup.html.panel.Panel;
import org.apache.wicket.model.CompoundPropertyModel;
import org.apache.wicket.model.IModel;
import org.apache.wicket.model.PropertyModel;
import org.apache.wicket.model.StringResourceModel;
import org.apache.wicket.spring.injection.annot.SpringBean;

import com.googlecode.chigs.domain.ConfigLocation;
import com.googlecode.chigs.domain.ConfigLocationGroup;
import com.googlecode.chigs.domain.Product;
import com.googlecode.chigs.domain.Version;
import com.googlecode.chigs.web.doku.version.VersionSelector;
import com.googlecode.chigscommons.repository.GenericDomainService;
import com.googlecode.chigscommons.web.common.IconFactory;
import com.googlecode.chigscommons.web.common.ValidationStyleBehavior;
import com.googlecode.chigscommons.web.common.forms.ShinyForm;

/**
 * @author Ingo Renner
 * @author Henning Teek
 */
@AuthorizeInstantiation("ROLE_ADMIN")
public class EditOrCreateLocationPanel extends Panel {
	public EditOrCreateLocationPanel(String id) {
		this(id, new CompoundPropertyModel<ConfigLocation>(new ConfigLocation()));
	}

	public EditOrCreateLocationPanel(String id, IModel<ConfigLocation> model) {
		super(id);
		add(new EditOrCreateConfigLocationForm("form", new CompoundPropertyModel<ConfigLocation>(model.getObject())));
	}

	class EditOrCreateConfigLocationForm extends ShinyForm<ConfigLocation> {
		@SpringBean
		private GenericDomainService genericDomainService;

		private Product product;

		public EditOrCreateConfigLocationForm(String id, IModel<ConfigLocation> model) {
			super(id, model);
			
			this.product = getModelObject().getVersion() != null ? getModelObject().getVersion().getProduct() : null;
			
			add(getProductSelector().setRequired(true));
			add(this.product != null ? getVersionSelector() : new Label("version", new StringResourceModel("version.choose", EditOrCreateConfigLocationForm.this, null)));
			
			StringResourceModel lName = new StringResourceModel("name.label", EditOrCreateConfigLocationForm.this, null);
			add(new Label("name.label", lName));
			add(new TextField<String>("name")
					.setRequired(true)
					.setLabel(lName)
					.add(new ValidationStyleBehavior()));

			StringResourceModel lloc = new StringResourceModel("location.label", EditOrCreateConfigLocationForm.this, null);
			add(new Label("location.label", lloc));
			add(new TextField<String>("location")
					.setRequired(true)
					.setLabel(lloc)
					.add(new ValidationStyleBehavior()));

			List<ConfigLocationGroup> configLocationGroups = genericDomainService.loadAll(ConfigLocationGroup.class);
			add(new DropDownChoice<ConfigLocationGroup>("configLocationGroup", new PropertyModel<ConfigLocationGroup>(getModelObject(), "configLocationGroup"), configLocationGroups, new ChoiceRenderer<ConfigLocationGroup>("name", "id")).setNullValid(true));

			add(new DropDownChoice<ConfigLocation.ConfigLocationType>("type", new PropertyModel<ConfigLocation.ConfigLocationType>(getModelObject(), "type"), Arrays.asList(ConfigLocation.ConfigLocationType.values())).setRequired(true));
			
			add(new Image("submit", IconFactory.createOkIconReference()));
			Link<Void> cancelLink = new Link<Void>("cancelButton") {
				@Override
				public void onClick() {
					returnToManagement();
				}
			};
			cancelLink.add(new Image("icon", IconFactory.createCancelIconReference()));
			add(cancelLink);
		}

		@Override
		protected void onSubmit() {
			try {
				genericDomainService.save(ConfigLocation.class, getModelObject());
				getSession().info(new StringResourceModel("save.success", EditOrCreateConfigLocationForm.this, null).getString());
				returnToManagement();
			} catch (Exception e) {
				error(e.getMessage());
			}
		}
		
		private DropDownChoice<Product> getProductSelector() {
			List<Product> products = genericDomainService.loadAll(Product.class);
			if (products.size() == 1){ // Selection nicht nötig
				EditOrCreateConfigLocationForm.this.product = products.get(0);
			}
			return new DropDownChoice<Product>("product",
					new PropertyModel<Product>(this, "product"),
					products,
					new ChoiceRenderer<Product>("name", "id")){
				@Override
				protected void onSelectionChanged(Product prod) {
					EditOrCreateConfigLocationForm.this.product = prod;
					EditOrCreateConfigLocationForm.this.addOrReplace(getVersionSelector());
				}
				@Override
				protected boolean wantOnSelectionChangedNotifications() {
					return true;
				}
			};
		}

		private VersionSelector getVersionSelector() {
			return new VersionSelector("version", new PropertyModel<Version>(getModelObject(), "version"), product);
		}

		private void returnToManagement() {
			final Panel p = new ManageLocationsPanel(EditOrCreateLocationPanel.this.getId());
			p.setOutputMarkupId(true);
			EditOrCreateLocationPanel.this.getParent().addOrReplace(p);
			this.setVisible(false);
		}
	}
}
